﻿/// ---------------------------------------------------
/// common.js
/// 
/// Create on:		25/05/2556 15:13:15
/// Original author: Wirat Khongthai
/// Email: wirat.k@g-able.com 
/// ---------------------------------------------------
/// Modification histories:
/// 
/// 
/// ---------------------------------------------------

Ext.onReady(function () {
    //Function for enter focus next controls.
    Ext.getDoc().on('keypress', function (event, target) {
        // get the form field component
        var targetEl = Ext.get(target.id),
            fieldEl = targetEl.up('[class*=x-field]') || {},
            field = Ext.getCmp(fieldEl.id);

        if (
            // the ENTER key was pressed...
            event.ENTER == event.getKey() &&

            // from a form field...
            field &&

            // which has valid data.
            field.isValid()

            ) {

            // get the next form field
            var next = field.next('[isFormField]');

            // focus the next field if it exists
            if (next) {
                event.stopEvent();
                next.focus();
            }
        }
    });
    Ext.apply(Ext.util.Format, { number: function (v, format) { if (!format) { return v; } v *= 1; if (typeof v != 'number' || isNaN(v)) { return ''; } var comma = ','; var dec = '.'; var i18n = false; if (format.substr(format.length - 2) == '/i') { format = format.substr(0, format.length - 2); i18n = true; comma = '.'; dec = ','; } var hasComma = format.indexOf(comma) != -1, psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec); if (1 < psplit.length) { v = v.toFixed(psplit[1].length); } else if (2 < psplit.length) { throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format); } else { v = v.toFixed(0); } var fnum = v.toString(); if (hasComma) { psplit = fnum.split('.'); var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3; for (var i = 0; i < j; i += n) { if (i != 0) { n = 3; } parr[parr.length] = cnum.substr(i, n); m -= 1; } fnum = parr.join(comma); if (psplit[1]) { fnum += dec + psplit[1]; } } return format.replace(/[\d,?\.?]+/, fnum); }, numberRenderer: function (format) { return function (v) { return Ext.util.Format.number(v, format); }; } });

    Ext.define('Ext.browse.Window', {
        extend: 'Ext.window.Window',
        alias: 'widget.browsewindow',
        width: 600,
        height: 490,
        title: '',
        closeAction: 'hide',
        modal: true,
        border: false,
        bodyBorder: false,
        minimizable: false,
        resizable: true,
        layout: 'fit',
        cfg: null,

        constructor: function (config) {
            cfg = config;
            this.callParent(Ext.apply(config));
        },

        initComponent: function () {
            this.callParent();
            this.title=cfg.title + ' [' + Ext.getCmp('frmsearchtitleinfo').text + ']';
            var searchcaption = Ext.getCmp('btnsearch').text;
            var closecaption = Ext.getCmp('btnclose').text;
            Ext.define('BrowseModel', {
                extend: 'Ext.data.Model',
                fields: [
                   { name: 'ischeck', type: 'boolean' },
                   { name: 'fieldname' },
                   { name: 'condition' },
                   { name: 'criteriavalue' },
                   { name: 'operation' }
                ]
            });
            var myData = [
               [false, 'รหัสบริษัท', '%LIKE%', '', 'AND'],
               [false, 'ชื่อบริษัท', '%LIKE%', '', 'AND'],
            ]
            var storeCriteria = Ext.create('Ext.data.ArrayStore', {
                model: 'BrowseModel',
                data: myData
            });
            var _store = Ext.create('Ext.data.Store', {
                pageSize: 20,
                autoLoad: true,
                remoteSort: false,
                proxy: {
                    type: 'ajax',
                    url: cfg.url,
                    reader: {
                        type: 'json',
                        root: 'data',
                        totalProperty: 'totalCount'
                    },
                    simpleSortMode: true
                },
                fields: cfg.field
                //sorters: [{
                //    property: 'OU_CODE',
                //    direction: 'ASC'
                //}]
            });
            var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1
            });
            var pnlContent = new Ext.panel.Panel({
                layout: 'border',
                tbar: [{
                    text: searchcaption,
                    iconCls: 'save16',
                    listeners: {
                        "click": function () {
                            var win = this.up('panel').up('window');
                            var grid = Ext.getCmp("grdBrowseResult");
                            var record = grid.selModel.getSelection()[0];
                            win.fireEvent('selected', record);
                            win.hide();
                        }
                    }
                },
                {
                    text: closecaption,
                    iconCls: 'cancel16',
                    listeners: {
                        "click": function () {
                            this.up('panel').up('window').hide();
                        }
                    }
                }],
                items: [
                     {
                         xtype: 'gridpanel',
                         frame: true,
                         region: 'north',
                         split: true,
                         columnLines: true,
                         region: 'north',
                         height: 120,
                         store: storeCriteria,
                         selModel: Ext.create('Ext.selection.RowModel'),
                         plugins: [cellEditing],
                         columns: [
                             {
                                 xtype: 'checkcolumn',
                                 header: '#',
                                 sortable: false,
                                 dataIndex: 'ischeck',
                                 width: 40,
                                 editor: {
                                     xtype: 'checkbox',
                                     cls: 'x-grid-checkheader-editor'
                                 }
                             },
                             {
                                 header: Ext.getCmp('grdcolfieldnamecaption').text,
                                 dataIndex: 'fieldname',
                                 sortable: false,
                                 width: 140,
                                 editor: new Ext.form.field.ComboBox({
                                     typeAhead: true,
                                     triggerAction: 'all',
                                     selectOnTab: true,
                                     store: myData,
                                     lazyRender: true,
                                     listClass: 'x-combo-list-small'
                                 })
                             },
                              {
                                  header: Ext.getCmp('grdcolconditioncaption').text,
                                  dataIndex: 'Condition',
                                  sortable: false,
                                  width: 80,
                                  editor: new Ext.form.field.ComboBox({
                                      typeAhead: true,
                                      triggerAction: 'all',
                                      selectOnTab: true,
                                      store: [
                                          ['%LIKE%', '%LIKE%'],
                                          ['LIKE%', 'LIKE%'],
                                          ['%LIKE', '%LIKE'],
                                          ['=', '='],
                                          ['>', '>'],
                                          ['<', '<'],
                                          ['<>', '<>'],
                                          ['>=', '>='],
                                          ['<=', '<=']
                                      ],
                                      lazyRender: true,
                                      listClass: 'x-combo-list-small'
                                  })
                              },
                               {
                                   header: Ext.getCmp('grdcolcriteriavaluecaption').text,
                                   dataIndex: 'criteriavalue',
                                   sortable: false,
                                   flex: 1,
                                   editor: new Ext.form.field.Text({
                                       selectOnTab: true
                                   })
                               },
                             {
                                 header: Ext.getCmp('grdcoloperationcaption').text,
                                 dataIndex: 'Operation',
                                 sortable: false,
                                 width: 80,
                                 editor: new Ext.form.field.ComboBox({
                                     typeAhead: true,
                                     triggerAction: 'all',
                                     selectOnTab: true,
                                     store: [
                                         [Ext.getCmp('operationandcaption').text, 'AND'],
                                         [Ext.getCmp('operationorcaption').text, 'OR']
                                     ],
                                     lazyRender: true,
                                     listClass: 'x-combo-list-small'
                                 })
                             }
                         ]
                     },
                    {
                        xtype: 'gridpanel',
                        id:'grdBrowseResult',
                        frame: true,
                        region: 'center',
                        columnLines: true,
                        flex: 1,
                        store: _store,
                        columns: cfg.columns,
                        bbar: Ext.create('Ext.PagingToolbar', {
                            store: _store,
                            displayInfo: true
                        })
                    }
                ]
            });
            this.add(pnlContent);
            this.addEvents(
               /**
                * @event selected
                * Fired whenever the user selects an image by double clicked it or clicking the window's OK button
                * @param {Ext.data.Model} image The image that was selected
                */
               'selected'
           );
        }
    });
});

//Function for sync gridview after window resize.
var syncWindowResize = function (sender) {
    var windowWidth = Ext.getDoc().getViewSize(false).width;
    var panelTabHeight = Ext.getCmp('ExampleTabs').down('panel').getHeight();
    sender.down('grid').setSize(windowWidth, panelTabHeight - sender.down('panel').getHeight()-25);
    Ext.EventManager.onWindowResize(function () {
        sender.down('grid').setSize(Ext.EventManager.curWidth, Ext.getCmp('ExampleTabs').down('panel').getHeight() - sender.down('panel').getHeight() - 25);
    });
};

var fireEventGridDbClick = function () {
    if (Ext.getCmp("btneditmain").disabled == false) {
        document.body.style.cursor = 'wait';
        var result = Ext.getCmp("btneditmain").handler.call(Ext.getCmp("btneditmain").scope);
        document.body.style.cursor = 'default';
    }
};